package com.hackathon.sgstern.search;

import java.util.ArrayList;
import java.util.List;

import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.hackathon.sgstern.R;
import com.hackathon.sgstern.Search;
import com.hackathon.sgstern.dataprovider.DataProvider;
import com.hackathon.sgstern.model.SportEvent;
import com.hackathon.sgstern.overview.SportEventListAdapter;

public class LocationBasedFragment extends Fragment {

	EditText distanceTextView;

	ListView searchResult;

	Button button;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(
				R.layout.fragment_search_locationbased, container, false);
		distanceTextView = (EditText) rootView.findViewById(R.id.distanceText);

		distanceTextView
				.setOnEditorActionListener(new OnEditorActionListener() {

					public boolean onEditorAction(TextView v, int actionId,
							KeyEvent event) {
						executeSearch();
						return false;
					}
				});
		searchResult = (ListView) rootView
				.findViewById(R.id.locationbasedsearch_result);
		button = (Button) rootView.findViewById(R.id.locationBasedSearch);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				executeSearch();
			}
		});
		return rootView;
	}

	public void executeSearch() {
		Search search = (Search) getActivity();
		Location loc = search.getLocation();

		String distance = distanceTextView.getText().toString();
		int distanceInMeters = Integer.parseInt(distance) * 1000;
		List<SportEvent> result = new ArrayList<SportEvent>();
		for (SportEvent event : DataProvider.getInstance().getEvents()) {
			Location tmpLoc = new Location("loc");
			tmpLoc.setLatitude(event.getOrt().latitude);
			tmpLoc.setLongitude(event.getOrt().longitude);

			if (loc.distanceTo(tmpLoc) < distanceInMeters) {
				result.add(event);
			}
		}
		searchResult
				.setAdapter(new SportEventListAdapter(getActivity(), result));
	}
}
